package net.sk.china.front.service.impl.wechat;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import net.sk.china.common.exception.TalkException;
import net.sk.china.front.constants.Constants;
import net.sk.china.front.response.WeChatMiniAuthorizeResponse;
import net.sk.china.front.service.wechat.WechatService;
import net.sk.china.front.service.system.SystemConfigService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * WechatServiceImpl 接口实现
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2018-2024 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2024/6/4 16:01
 * // +----------------------------------------------------------------------
 */

@Service
public class WechatServiceImpl implements WechatService {

    private final SystemConfigService systemConfigService;

    private final RestTemplate restTemplate;

    public WechatServiceImpl(SystemConfigService systemConfigService, RestTemplate restTemplate) {
        this.systemConfigService = systemConfigService;
        this.restTemplate = restTemplate;
    }

    /**
     * 小程序登录凭证校验
     * @param code code码
     * @return {@code WeChatMiniAuthorizeResponse}
     */
    @Override
    public WeChatMiniAuthorizeResponse miniAuthCode(String code) {
        String appId = systemConfigService.getValueByKey(Constants.WECHAT_MINI_APPID);
        if (StrUtil.isBlank(appId)) {
            throw new TalkException("微信小程序appId未设置");
        }
        String secret = systemConfigService.getValueByKey(Constants.WECHAT_MINI_APPSECRET);
        if (StrUtil.isBlank(secret)) {
            throw new TalkException("微信小程序secret未设置");
        }
        String url = StrUtil.format(Constants.WECHAT_MINI_SNS_AUTH_CODE2SESSION_URL, appId, secret, code);
        String data = getData(url);
        if (StrUtil.isBlank(data)) {
            throw new TalkException("微信平台接口异常，没任何数据返回！");
        }
        WeChatMiniAuthorizeResponse response = JSONObject.parseObject(data, WeChatMiniAuthorizeResponse.class);
        if (ObjectUtil.isNotNull(response.getErrCode()) && !response.getErrCode().equals(Constants.ZERO)) {
            throw new TalkException(String.format("微信小程序登录凭证校验异常：%s %s", response.getErrCode(), response.getErrMsg()));
        }

        return response;
    }


    /**
     * 发送GET请求
     * @param url 请求地址
     * @return JSONObject
     */
    private String getData(String url) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>( headers);

        return restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class).getBody();
    }
}
